<script setup>
import { computed, onMounted, watch, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useChatStore } from '@/stores/chat'
import BottomTabBar from '@/components/BottomTabBar.vue'
import { connectGlobalWs, addWsListener } from '@/utils/globalWs'
import { ElNotification } from 'element-plus'
import { h, onUnmounted } from 'vue'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const chatStore = useChatStore()

const isLogin = computed(() => route && route.name === 'Login')

const saveTokenAndUserId = async () => {
  const token = route && route.query ? route.query.token : undefined
  const userid = route && route.query ? route.query.userid : undefined
  const isThirdParty = route && route.query ? route.query.thirdparty === '1' : false
  if (token) {
    localStorage.setItem('token', token.replace(/^Bearer\s+/i, ''))
    userStore.setLoginStatus(true)
    if (userid) {
      localStorage.setItem('userid', userid)
      if (token && userid) {
        try {
          await userStore.fetchThirdPartyProfile(userid)
          userStore.isThirdParty = true
          userStore.openid = userid
        } catch (error) {
          userStore.setUserInfo({
            nickname: `用户${userid}`,
            location: '北京',
            thirdParty: false
          })
        }
      } else {
        userStore.setUserInfo({
          nickname: `用户${userid}`,
          location: '北京',
          thirdParty: false
        })
      }
    }
  }
  // 全局拦截：只要有token和userid参数，强制跳转到/home
  if (token && userid && route && route.path !== '/home') {
    router.replace({ path: '/home' })
  }
}

function handleGlobalChatMessage() {
  // TODO: 处理全局聊天消息
}

onMounted(async () => {
  await saveTokenAndUserId();
  const token = localStorage.getItem('token')
  const userid = localStorage.getItem('userid')
  if (token && userid) {
    userStore.setLoginStatus(true)
    await userStore.fetchThirdPartyProfile(userid)
    userStore.isThirdParty = true
    userStore.openid = userid
    // 全局 WebSocket 连接
    connectGlobalWs()
    console.log('[App.vue] addWsListener 注册前', 'chat_message', handleGlobalChatMessage)
    addWsListener('chat_message', handleGlobalChatMessage)
    console.log('[App.vue] addWsListener 注册后', 'chat_message', handleGlobalChatMessage)
  }
})

onUnmounted(() => {
  // 可选：如需断开全局 ws，可在此处调用 closeWs()
})

watch(() => (route && route.query) ? route.query : {}, saveTokenAndUserId, { immediate: true, deep: true })
</script>

<template>
  <div class="app-layout">
    <!-- 顶部导航栏：已去除 -->
    <router-view />
    <!-- 底部导航栏：只在非登录页面显示 -->
    <BottomTabBar v-if="!isLogin" />
  </div>
</template>

<style scoped>
.app-layout {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f7f7f7;
}
</style>
